<template>
  <div class="info">
    <!-- <p class="logo-box"></p> -->
    <div class="logo-wrap">
      <img :src="logoImg" class="logoImg" />
      <!-- <h2 style="text-align: center; color: #84aaff">{{ settings.title }}</h2> -->
    </div>
    <el-row class="hander">
      <el-col :span="11" class="hander-item" @click="activeName = 'LDAP'"
        ><span :class="activeName === 'LDAP' ? 'isActive' : ''"
          >LDAP</span
        ></el-col
      >
      <el-col :span="2" class="hander-center">|</el-col>
      <el-col :span="11" class="hander-item" @click="activeName = 'DEFAULT'"
        ><span :class="activeName === 'DEFAULT' ? 'isActive' : ''"
          >普通登录</span
        ></el-col
      >
    </el-row>
    <div
      v-show="activeName === 'LDAP'"
      class="ldap-wrap"
      :class="activeName === 'LDAP' ? 'animationLdap' : ''"
    >
      <el-button
        class="ldapBtn"
        size="medium"
        type="primary"
        @click.prevent="handleToLdap"
        >LDAP登录</el-button
      >
    </div>
    <div
      v-show="activeName === 'DEFAULT'"
      :class="activeName === 'DEFAULT' ? 'animation' : ''"
    >
      <el-form
        :model="model"
        :rules="rulesRules"
        ref="ruleForm"
        @keyup.enter="onBehavior"
      >
        <el-form-item prop="userName">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.userName"
            placeholder="请输入用户名"
            class="no-border"
            maxlength="64"
            autofocus
            prefix-icon="el-icon-user"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            clearable
            size="medium"
            type="password"
            show-password
            v-model.trim="model.passWord"
            placeholder="请输入密码"
            class="no-border"
            maxlength="64"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item class="custom-item" prop="identify">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.identify"
            placeholder="验证码"
            style="width: 235px; display: inline-block; vertical-align: middle"
            maxlength="64"
          ></el-input>
          <Identify
            class="identify-box"
            :contentWidth="94"
            :contentHeight="36"
            backgroundColor="#08132A"
            :drawLine="true"
            :drawDot="false"
            :identifyCode="activeData.identifyCode"
            @click="refreshCode"
          ></Identify>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button
            class="custom-item--btn"
            size="medium"
            type="primary"
            @click.prevent="onBehavior"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import settings from "/@/settings";
import logoImg from "/@/assets/logo.png";

import {
  ref,
  defineComponent,
  PropType,
  onBeforeMount,
  onMounted,
  getCurrentInstance,
  // watch,
  // nextTick,
  toRef
} from "vue";
import { storageSession } from "/@/utils/storage";
import Identify from "/@/components/Identify/index.vue";

export interface ContextProps {
  userName: string;
  passWord: string;
  telephone?: number;
  dynamicText?: string;
  identify: string;
}

import { useRouter } from "vue-router";

// import { initRouter } from "/@/router";

export default defineComponent({
  name: "Info",
  props: {
    ruleForm: {
      type: Object as PropType<ContextProps>,
      require: true
    }
  },
  emits: ["onBehavior"],
  components: { Identify },
  setup(props, ctx) {
    let vm: any;
    let activeName = ref("LDAP");

    const activeData = ref({
      identifyCodes: "1234567890abcdef",
      identifyCode: "",
      checked: false
    });

    const model = toRef(props, "ruleForm");
    let tips = ref("注册");
    // let tipsFalse = ref("登录");

    // const route = useRoute();
    const router = useRouter();

    // watch(
    //   route,
    //   async ({ path }): Promise<void> => {
    //     await nextTick();
    //     path.includes("register")
    //       ? (tips.value = "登录") && (tipsFalse.value = "注册")
    //       : (tips.value = "注册") && (tipsFalse.value = "登录");
    //   },
    //   { immediate: true }
    // );

    const identifyFunc = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入验证码"));
      } else {
        if (value !== activeData.value.identifyCode) {
          callback(new Error("请输入正确的验证码"));
        }
        callback();
      }
    };

    const rulesRules = {
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      passWord: [
        { required: true, message: "请输入密码", trigger: "blur" }
        // { min: 6, message: "密码长度必须不小于6位", trigger: "blur" }
      ],
      identify: [{ validator: identifyFunc, trigger: "blur" }]
    };

    // 点击登录或注册
    const onBehavior = (evt: Object) => {
      vm.refs.ruleForm.validate((valid: boolean) => {
        if (valid) {
          ctx.emit("onBehavior", evt);
        } else {
          return false;
        }
      });
    };

    // 表单重置
    const resetForm = (): void => {
      vm.refs.ruleForm.resetFields();
      refreshCode();
    };

    // 登录、注册页面切换
    const changPage = (): void => {
      tips.value === "注册" ? router.push("/register") : router.push("/login");
    };

    const noSecret = (): void => {
      storageSession.setItem("username", "admin");
      storageSession.setItem("accessToken", "eyJhbGciOiJIUzUxMiJ9.test");
      // initRouter().then(() => {});
      router.push("/");
    };

    const toRegister = () => {
      router.push("/register");
    };

    onBeforeMount(() => {
      vm = getCurrentInstance(); //获取组件实例
    });

    onMounted(() => {
      makeCode(4);
    });

    // 验证码处理
    const randomNum = (min, max) => {
      return Math.floor(Math.random() * (max - min) + min);
    };

    // 刷新验证码
    const refreshCode = () => {
      model.value.identify = "";
      activeData.value.identifyCode = "";
      makeCode(4);
    };

    const makeCode = l => {
      for (let i = 0; i < l; i++) {
        activeData.value.identifyCode +=
          activeData.value.identifyCodes[
            randomNum(0, activeData.value.identifyCodes.length)
          ];
      }
      // console.log(activeData.value.identifyCode);
    };

    const handleToLdap = () => {
      const { origin } = window.location;
      let loginUrl = `https://ldap-sit.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}/welcome&client_id=epmssit`;

      // uat 环境
      if (import.meta.env.VITE_PROJECT_ENV === "uat") {
        loginUrl = `https://ldap-uat.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}/welcome&client_id=epmsuat`;
      } else if (import.meta.env.VITE_PROJECT_ENV === "pre") {
        // 生产环境
        loginUrl = `https://ldap.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}/welcome&client_id=CRB_EMPSPRO`;
      }

      window.open(loginUrl, "_self");
    };

    return {
      logoImg,
      settings,
      model,
      rulesRules,
      tips,
      activeData,
      activeName,
      resetForm,
      onBehavior,
      changPage,
      noSecret,
      refreshCode,
      toRegister,
      handleToLdap
    };
  }
});
</script>

<style lang="scss" scoped>
.info {
  width: 500px;
  height: 480px;
  // background: url("../../assets/login.png") no-repeat center;
  // background-size: cover;
  background: #fff;
  position: absolute;
  border-radius: 8px;
  left: 50%;
  top: 50%;
  margin-left: -300px;
  margin-top: -220px;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  padding: 50px 80px 66px;
  // @media screen and (max-width: 750px) {
  //   width: 88vw;
  //   right: 25px;
  //   top: 22vh;
  // }
  overflow: hidden;
  .logo-box {
    width: 290px;
    height: 26px;
    background: url("../../assets/login-logo.png") no-repeat center;
    background-size: 290px 26px;
    margin-bottom: 32px;
  }
  .secret {
    color: #409eff;
    font-size: 14px;
    &:hover {
      cursor: pointer;
    }
  }

  .hander {
    margin: 30px 0;
    &-item {
      text-align: center;
      font-size: 14px;
      font-weight: bold;
      color: #5f5f5f;
      &:hover {
        cursor: pointer;
        color: #5eaaf5;
      }
    }
    &-center {
      text-align: center;
      font-size: 14px;
      color: #5f5f5f;
    }
    .isActive {
      color: #84aaff;
    }
  }
}

.ldap-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  .ldapBtn {
    margin-top: 80px;
    width: 60%;
  }
}

.custom-item {
  display: flex;
  justify-content: flex-end;
  &--btn {
    width: 100%;
  }
}
.identify-box {
  display: inline-block;
  vertical-align: middle;
  height: 36px;
  margin-left: 8px;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;
}

.logo-wrap {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;

  .logoImg {
    width: 322px;
    margin-right: 8px;
  }
}

// 登录页样式覆盖
:deep .el-input--medium.no-border .el-input__inner {
  padding-left: 30px !important;
  padding-right: 12px;
}

:deep .el-input {
  input {
    background: transparent;
    &:-webkit-autofill {
      box-shadow: 0 0 0 1000px #fff inset;
      -webkit-text-fill-color: #000;
    }
  }
}

:deep .el-input--medium.no-border .el-input__inner {
  border-left: none;
  border-top: none;
  border-right: none;
  border-radius: 0;
  padding-left: 0;
}
:deep .el-input el-input--medium el-input--suffix no-border {
  border-left: none;
  border-top: none;
  border-right: none;
  border-radius: 0;
  padding-left: 0;
}

.animationLdap {
  position: relative;
  animation: myLdap 0.5s;
}
.animation {
  position: relative;
  animation: myfirst 0.5s;
}

@keyframes myfirst {
  from {
    // left: 200px;
    //  transform: rotateY(130deg);
    transform: translateX(200px);
    opacity: 0;
  }
  to {
    // left: 0px;
    transform: translateX(0px);
    opacity: 1;
  }
}

@keyframes myLdap {
  from {
    right: 200px;
    opacity: 0;
  }
  to {
    right: 0px;
    opacity: 1;
  }
}
</style>
